package org.wsff.tools.api.gateway.manager;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.wsff.tools.api.gateway.core.ProxyFilter;
import org.wsff.tools.api.gateway.core.ProxyInvoker;
import org.wsff.tools.api.gateway.core.ProxyValidator;

/**
 * Proxy 包装器
 *
 * @author ryan
 * @version Id: ProxyWrapper.java, v 0.1 2022-04-03 15:59 ryan Exp $$
 */
public class ProxyWrapper<Request extends Serializable, Response extends Serializable> {

    /** 服务状态 */
    private State                                       state;
    /**  服务id */
    private String                                      id;

    private ProxyInvoker<Request, Response>             proxyInvoker;
    private ProxyValidator<Request>                     proxyValidator;
    private Map<String, ProxyFilter<Request, Response>> proxyFilters;

    public ProxyWrapper(ProxyInvoker<Request, Response> proxyInvoker, String id) {
        this.proxyInvoker = proxyInvoker;
        this.state = State.ONLINE;
        this.id = id;
    }

    public static <Response extends Serializable, Request extends Serializable> ProxyWrapper<Request, Response> create(ProxyInvoker<Request, Response> invoker, String name) {
        return new ProxyWrapper<>(invoker, name);
    }

    /**
     * Sets the proxyValidator. *
     * <p>You can use getProxyValidator() to get the value of proxyValidator</p >
     * @param proxyValidator proxyValidator
     */
    public void addProxyValidator(ProxyValidator<Request> proxyValidator) {
        this.proxyValidator = proxyValidator;
    }

    /**
     * Sets the proxyFilters. *
     * <p>You can use getProxyFilters() to get the value of proxyFilters</p >
     * @param name name
     * @param proxyFilter proxyFilter
     */
    public void addProxyFilters(String name, ProxyFilter<Request, Response> proxyFilter) {
        if (this.proxyFilters == null) {
            this.proxyFilters = new HashMap<>();
        }
        if (this.proxyFilters.containsKey(name)){
            return;
        }
        this.proxyFilters.put(name, proxyFilter);
    }

    /**
     * 下线服务
     */
    public void offline() {
        state = State.OFFLINE;
    }

    /**
     * 服务是否下线
     */
    public boolean isOffline() {
        return state == State.OFFLINE;
    }

    /**
     * Gets the value of proxyInvoker.
     *
     * @return the value of proxyInvoker
     */
    public ProxyInvoker<Request, Response> get() {
        return proxyInvoker;
    }

    /**
     * Gets the value of proxyValidator.
     *
     * @return the value of proxyValidator
     */
    public ProxyValidator<Request> getProxyValidator() {
        return proxyValidator;
    }

    /**
     * Gets the value of proxyFilters.
     *
     * @return the value of proxyFilters
     */
    public Map<String, ProxyFilter<Request, Response>> getProxyFilters() {
        return proxyFilters;
    }

    enum State {
                ONLINE, OFFLINE;
    }
}
